package task3;

import java.io.*;

public class CopyThread extends Thread {
    private File file;
    private String original;
    private String destination;

    public CopyThread(File file, String original, String destination){
        this.file = file;
        this.original = original;
        this.destination = destination;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getOriginal() {
        return original;
    }

    public void setOriginal(String original) {
        this.original = original;
    }

    public String getDestination() {
        return destination;
    }

    public void setDestination(String destination) {
        this.destination = destination;
    }

    @Override
    public void run(){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream(file.getAbsolutePath().replace(original, destination)));
            System.out.println(Thread.currentThread().getName() + "线程正在复制文件：" + file.getAbsolutePath());
            byte[] bArr = new byte[1024];
            int res = 0;
            while ((res = bis.read(bArr, 0, bArr.length)) == -1) {
                bos.write(bArr, 0, res);
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("---" + Thread.currentThread().getName() + "线程复制完成：" + file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != bos){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != bis){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
